﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.Menu;
using B.S.BasicData.Read.DTOS;
using MediatR;

namespace B.S.BasicData.Read.Apilication.Handler.Menu
{
    public class TreeMenuHandler : IRequestHandler<TreeMenuCommon, ApiResult<List<TreeMenuDTO>>>
    {
        private readonly IBaseRepository<menuModel> menuRepo;
        private readonly IMapper mapper;

        public TreeMenuHandler(IBaseRepository<menuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<TreeMenuDTO>>> Handle(TreeMenuCommon request, CancellationToken cancellationToken)
        {
            ApiResult<List<TreeMenuDTO>> res=new ApiResult<List<TreeMenuDTO>>();

            res.Code=ApiEnum.Success;
            res.Message = "菜单树形展示成功";
            res.Data = gettree(0);
            return Task.FromResult(res);


        }

        private List<TreeMenuDTO> gettree(int parment)
        {
            var info = menuRepo.GetAll().Where(x=>x.ParentId==parment).ToList();
            var model=mapper.Map<List<TreeMenuDTO>>(info);
            foreach (var item in model)
            {
                item.Children = gettree(item.MenuId);
            }
            return model;
        }
    }
}
